package com.runa.rccprotocol.analysis.En13757.decoder;

import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.analysis.En13757.HeadInfo;
import com.runa.rccprotocol.analysis.En13757.UnitData;

import java.text.NumberFormat;
import java.util.Date;
import java.util.List;

/**
 * @author diandian
 * @Date 2021/11/9 19:24
 */
public class DefaultEnDecoder extends AbsEnDecoder {
    public DefaultEnDecoder() {
    }

    private int dataLength = 0;

    @Override
    public int check() {
        int start = 0x68;
        while (hasNext()) {
            byte data = next();
            if (start == data) {
                break;
            }
        }
        //获取当前下标
        int startIndex = super.getCurrentIndex();

        //获取数据长度
        int dataLength = super.next() & 0xff;
        int dataLength2 = super.next() & 0xff;

        int start2 = super.next() & 0xff;

        if (start != start2 || dataLength != dataLength2) {
            return length - 4;
        }

        this.dataLength = dataLength2;
        //校验数据长度 欧标的数据头占 19 个字节
        //数据长度不够，需要返回-1，重新续长度
        int headLength = 4;
        int tailLength = 2;
        if (length < headLength + dataLength + tailLength + startIndex) {
            return -1;
        }

        //cs校验
        int csIndex = headLength + dataLength;
        boolean csResult = dataByte[csIndex] == super.sum(headLength, dataLength);
        if (!csResult) {
            return length - csIndex - 2;
        }
        return 0;
    }

    @Override
    public HeadInfo getHeadInfo() {
        HeadInfo headInfo = new HeadInfo();
        //标准欧标头有19个字节
        headInfo.setHeadLength(19);  //12 byte (CI = 72h)
        //check方法中已经初始化过当前下标到 68了

        //移动到长度下标
//        super.addCurrentIndex(1);

        //数据长度
//        int dataLength = super.nextInt(2, true);
        // 2个字节的尾巴
        dataLength = dataLength - 2 - headInfo.getHeadLength()+4;
        headInfo.setDataLength(dataLength);

        //分隔符
//        super.addCurrentIndex(1);

        //C域  从站发送数据到主站
        byte c_field = super.next();
        headInfo.setC_field(c_field);

        //主地址域
        byte address = super.next();
        headInfo.setAddress(address);

        //CI域
        byte ci = super.next();
        headInfo.setCi_field(ci);

        //ID号
        String serialNo = super.nextHexString(4, false);
        headInfo.setSerialNo(serialNo);

        //制造商号
        String manufacture = super.nextHexString(2, false);
        headInfo.setManufacture(manufacture);

        //版本号
        byte version = super.next();
        headInfo.setVersion(version);

        //设备类型
        byte medium = super.next();
        headInfo.setMedium(medium);

        //访问序号
        byte accesses = super.next();
        headInfo.setAccesses(accesses);

        //状态
        byte status = super.next();
        headInfo.setStatus(status);

        //签名
        int signature = super.nextInt(2, true);
        headInfo.setSignature(signature);

        headInfo.setHeadEndIndex(super.getCurrentIndex());

        return headInfo;
    }

    @Override
    public void decodeUnitValue(UnitData unitValue) {
        //标准协议，不做处理
    }

    public static void main(String[] args) {
//        String s = "0C  06  89  67  45  23  0C  14  89  78  56  13  0B  59  23  56  00   0B  5D  68  53  00  0A  61  55  02  0B  2C  35  16  00  0B  3A  29  02  00  0B  22  23  06  00  3B  22  15  00  00  04  6D  1A  26  8A  18  0C  86  69  58  36  15".replace("  ","");
//        String s = "0CFB08741205008C10FB08000000008C2016030000000C16934205000C2D000000000B3D0000000A5A80020A5E92020A27 95 14 0AA6180000".replace("  ","");
//        String s = "0C06266507000C14870197010C2B203500000B3B3205000A5A05040A5E47030A6257000A274927046D1113C6214C06502507004C1450429101426CBF25".replace("  ","");
        String s = "09 70 08 0C 06 47 80 07 00 0C 14 59 47 84 01 0B 2D 00 00 00 0B 3B 02 00 F0 0B 5A 77 01 00 0B 5E 79 01 00 0B 62 01 00 F0 0C 78 98 56 17 67 89 10 71 07 3C 22 81 24 01 00 0C 22 67 31 08 00 0C 26 26 23 03 00 8C 90 10 06 71 00 00 00 9B 10 2D 39 01 00 9B 10 3B 92 10 00 9B 10 5A 53 08 00 9B 10 5E 33 06 00 94 10 AD 6F 00 05 F4 1B 94 10 BB 6F 07 01 EF 1C 94 10 DA 6F 28 06 DD 11 94 10 DE 6F 0A 09 B4 1B 4C 06 09 27 07 00 4C 14 11 44 73 01 7C 22 81 24 01 00 4C 26 05 99 02 00 CC 90 10 06 71 00 00 00 DB 10 2D 39 01 00 DB 10 3B 92 10 00 DB 10 5A 53 08 00 DB 10 5E 33 06 00 84 8F 0F 6D 00 00 E1 F1 04 6D 0A 15 DA 24 1F 11 07 00 77 01".replace("  ","");

        byte[] bytes = ByteUtil.hexStringToByte(s);
        System.out.println(bytes.length);

        DefaultEnDecoder enDecoder = new DefaultEnDecoder();
        enDecoder.init(bytes, bytes.length);

        NumberFormat format = NumberFormat.getInstance();


        List<UnitData> unitData = enDecoder.getUnitData(bytes.length,-1);
        unitData.forEach(v -> {
            System.out.println("DIF:" + String.format("%02X", v.getDif().getDifByte()) + "\t VIF:" + String.format("%02X", v.getVif().getVifByte()) + "\t valueByte:" + ByteUtil.byteToHexString(v.getDif().getDataByte()) +
                    "\t value:" + (v.getValue() instanceof Date ? v.getValue() : v.getValue() == null ? null : format.format(v.getValue())) +"\t valueType:"+v.getVif().getDataType() + "\t"+v.getDif().getDif_type());
        });

        String timeStr = "1113C621";
        byte[] buf = ByteUtil.hexStringToByte(timeStr);

        int sec=0;
        int min=buf[0]&0x3f;
        int hour=buf[1]&0x1f;
        int day=buf[2]&0x1f;
        int mon=buf[3]&0x0f;

        int year=buf[3]>>4;
        year<<=3;
        year+=buf[2]>>5;

        int dt[] = new int[6];
        dt[0]=sec;
        dt[1]=min;
        dt[2]=hour;
        dt[3]=day;
        dt[4]=mon;
        dt[5]=year;

        System.out.println();
    }
}